#! /usr/bin/env python
"""
    rconsole

    A Python console you can embed in a program and attach to remotely.

    To spawn a Python console in a script do the following in global scope
    only (!) of any module:

    from rfoo.utils import rconsole
    rconsole.spawn_server()

    This will start a listener for connections in a new thread. You may
    specify a port to listen on.

    To attach to the console from another shell use the rconsole script
    (rfoo/scripts/rconsole).

    SECURITY NOTE:
    The listener started with spawn_server() will accept any local 
    connection and may therefore be insecure to use in shared hosting
    or similar environments!
"""


import getopt
import sys
import os

import rfoo.utils.rconsole as rconsole


def print_usage():
    scriptName = os.path.basename(sys.argv[0])
    sys.stdout.write("""
Start remote console:
%(name)s [-h] [-pPORT]

-h, --help  Print this help.
-pPORT      Set PORT.
""" % {'name': scriptName})


def main():
    """Parse options and run script."""

    try:
        options, args = getopt.getopt(
            sys.argv[1:], 
            'hp:', 
            ['help']
            )
        options = dict(options)

    except getopt.GetoptError:
        print_usage()
        return 2

    if '-h' in options or '--help' in options:
        print_usage()
        return

    if '-p' in options:
        port = int(options.get('-p'))
    else:
        port = rconsole.PORT

    rconsole.interact(port=port)


if __name__ == '__main__':
    main()

    
